import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken, session } from "@/utils/auth";
import Vue from "vue";
import {
  resetRouter,
  asyncRoutes,
  constantRoutes,
  anyRoutes,
} from "@/router";
import router from "@/router";
import cloneDeep from "lodash/cloneDeep";
import request from "@/utils/request";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    resultAllRoutes: [],
    baseApi: request.defaults.baseURL,
    userInfo: {},
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  //最终计算出的异步路由
  SET_RESULTASYNCROUTES: (state, routes) => {
    //vuex保存当前用户的异步路由，注意，一个用户需要展示完成路由：常量、异步、任意路由
    //state.resultAsyncRoutes = routes;
    //计算出当前用户需要展示所有路由

    state.resultAllRoutes = constantRoutes.concat(routes,anyRoutes);
    //console.log(resultAllRoutes);
    //给路由器添加新的路由
    router.addRoutes(state.resultAllRoutes)
    //router.selfaddRoutes(state.resultAllRoutes);
  },
};

//定义一个函数：两个数组进行对比，对比出当前用户到底显示哪些异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
  //过滤出当前用户【超级管理|普通员工】需要展示的异步路由
  return asyncRoutes.filter((item) => {
    //数组当中没有这个元素返回索引值-1，如果有这个元素返回的索引值一定不是-1
    if (routes.indexOf(item.name) != -1) {
      //递归:别忘记还有2、3、4、5、6级路由
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes);
      }
      return true;
    }
  });
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo;
    let result = await login({ username: username.trim(), password: password });
    if (result.code == 200) {
      const { currentUser } = result;
      commit("SET_TOKEN", result.authorization);
      setToken(result.authorization);
      session.set("id", currentUser.id);
      session.set("menuList", result.menuList);
      session.set("perms", result.perms);
      return result.msg;
    } else {
      return Promise.reject(new Error(result.msg));
    }
  },

  // get user info
  async getInfo({ commit }, { id }) {
    let result = await getInfo(id);
    if (result.code == 200) {
      const { sysUser } = result.data;
      commit("SET_USERINFO", sysUser);
      commit("SET_NAME", sysUser.username);
      commit("SET_AVATAR", sysUser.avatar);
      commit(
        "SET_RESULTASYNCROUTES",
        computedAsyncRoutes(cloneDeep(asyncRoutes), session.get("perms"))
      );
      return result;
    } else {
      return Promise.reject(new Error(result.msg));
    }
  },

  // user logout
  async logout({ commit, state }, status) {
    let result = await logout();
    if (result.code == 200) {
      commit("RESET_STATE");
      removeToken();
      resetRouter();
      session.clear();
      status ? "" : Vue.prototype.msgSuccess(result.msg);
    } else {
      return Promise.reject(new Error(result.msg));
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
